package com.llc.uh.user;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.llc.uh.quiz.SendQuizDataServlet;
import java.util.List;

/**
 * This servlet responds to the posting of test answers.
 * 
 */
@SuppressWarnings("serial")
public class CheckValidUserServlet extends HttpServlet
{

    private static final Logger logger = Logger.getLogger(SendQuizDataServlet.class.getCanonicalName());

    private static String errorMsg1 = "You cannot leave either email address blank";
    private static String errorMsg2 = "The emails do not match.";
    private static String errorMsg3 = "The email format is not recognized.";
    private static String errorMsg4 = "A user with that email address already completed the quiz. You can not take it again.";
    
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {

        logger.log(Level.INFO, "Obtaining User listing");

        String dsEmail = null;
        boolean duplicateEmail = false;
        boolean emailIsOkay = true;
        String emailErrorMsg = null;

        // email that was entered
        String email = req.getParameter("email");
        String vEmail = req.getParameter("email2");
        System.err.println("begin: parameter email " + email);
        System.err.println("begin: parameter valid email " + vEmail);

        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

        Query query = new Query("User");
        List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(100));

        
        
        // get the email that was entered

        
        
        if ("".equals(email) || "".equals(vEmail))
        {
            //error
            emailErrorMsg = errorMsg1;
            emailIsOkay = false;
            System.err.println("        Empty parameter email");
            //resp.sendRedirect("/index.jsp" + "?error=" + errorMsg1);
        }
        else if(! matches(email, vEmail))
        {
            //error = "The two emails must be the same.";
            emailErrorMsg = errorMsg2;
            emailIsOkay = false;
            System.err.println("        non matching" + "empty");
            //resp.sendRedirect("/index.jsp" + "?error=" + errorMsg2);    
        }
        else if (! isValidEmail(email))
        {
            emailErrorMsg = errorMsg3;
            emailIsOkay = false;
            //error = "You must enter a valid email address.";
            System.err.println("         not valid");
            //resp.sendRedirect("/index.jsp" + "?error=" + error);    
        }
        else 
        {
            for (Entity user : users)
            {
                dsEmail = (String) user.getProperty("email");
                if (dsEmail.equals(email))
                {
                    //error
                    emailErrorMsg = errorMsg4;
                    emailIsOkay = false;
                    duplicateEmail = true;
                    System.err.println("Duplicate userEmail found in datastore" + " " + dsEmail);
                    break;
                }
            }

        }
        
        if(emailIsOkay)
        {
            resp.sendRedirect("/quiz.jsp" + "?email=" + email);
        }
        else
        {
            //add email to the response? resp.
            resp.sendRedirect("/index.jsp" + "?error=" + emailErrorMsg + "&email=" + email);
        }
        
        


    }
    private boolean isValidEmail(String emailAddress)
    {
        String pattern = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
        return emailAddress.contains(" ") == false && emailAddress.matches(pattern);

    }

    private boolean matches(String emailAddress1, String emailAddress2)
    {

        return emailAddress1.equals(emailAddress2);

    }
    
}
